import 'dart:async';
import 'dart:convert' as convert;

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wch/constant/event_bus_global.dart';
import 'package:wch/constant/mqtt_constant.dart';
import 'package:wch/constant/resource_constant.dart';
import 'package:wch/helper/flags_widget.dart';
import 'package:wch/helper/mqtt.dart';
import 'package:wch/model/deviceInfo.dart';
import 'package:wch/model/patient_device_list_entity.dart';
import 'package:wch/native/net_business.dart';
import 'package:wch/page/wifi_sest.dart';
import 'package:wch/utils/color_utils.dart';
import 'package:wch/utils/loading_utils.dart';
import 'package:wch/utils/log_utils.dart';
import 'package:wch/utils/toast_utils.dart';
import 'package:wch/widget/alert_view.dart';
import 'package:wch/widget/common_widget.dart';
import 'package:wch/widget/padding_widget.dart';
import 'package:wch/widget/text_widget.dart';

import '../helper/preferences_helper.dart';
import '../model/acquisition_entity.dart';
import '../model/flag_model.dart';
import '../model/patient_info_custom.dart';
import '../model/patient_label.dart';
import '../model/patient_label_list.dart';
import '../model/recycle_device_model.dart';
import '../utils/navigator_utils.dart';
import '../widget/recycle_device_alert.dart';
import 'delivery_device.dart';

class DeviceInfoPage extends StatefulWidget {
  const DeviceInfoPage(
      {super.key, required this.patientInfoCustom, required this.labelModel, this.labelList});

  // final String? name;
  // final String? sex;
  // final int? age;
  // final String? mobile;
  // final String id;
  final PatientInfoCustom patientInfoCustom;
  final PatientLabelModel labelModel;
  final List<AcquisitionAcquisitionLabelList>? labelList;

  @override
  State<DeviceInfoPage> createState() => _DeviceInfoPageState();
}

class _DeviceInfoPageState extends State<DeviceInfoPage>
    with AutomaticKeepAliveClientMixin {
  // List<Widget> models = [];
  double flagWidgetHeight = 0;
  PatientDeviceListEntity deviceListEntity = PatientDeviceListEntity();
  // List<String> topicList = [];
  String? topic;
  String? curDeviceId;
  String? curDeviceName;
  OverlayEntry? entry;
  String? recycleTime;
  String? recycleRemark;
  bool isQueryRecycle = false;//查询回收状态
  StreamSubscription? deviceInfoSubscription;
  StreamSubscription? refreshSubscription;
  StreamSubscription? recycleSubscription;
  Timer? queryTimer;
  Timer? recycleTimer;

  @override
  void initState() {

    initData();

    refreshSubscription = globalEventBus.on<EventBufRefreshModel>().listen((onData){
      ///刷新界面
      initData();
    });

  }

  void initData() {
    NetBusiness().patientDeviceList(widget.patientInfoCustom.userId).then((onValue) {
      setState(() {
        deviceListEntity = onValue;
      });
    });
  }
  @override
  void dispose() {
    super.dispose();
    // for (int i = 0; i < topicList.length; i++) {
    //   mqttCancelSubscribe(topicList[i]);
    // }

    if (topic != null) {
      LogUtils.log('222222');
      mqttCancelSubscribe(topic!);
    }
    deviceInfoSubscription?.cancel();
    refreshSubscription?.cancel();
    recycleSubscription?.cancel();
    queryTimer?.cancel();
    recycleTimer?.cancel();
  }

  @override
  bool get wantKeepAlive => true;


  @override
  Widget build(BuildContext context) {
    return Container(
        color: Color(0xFFF8F9FB),
        child: deviceListEntity.data == null || deviceListEntity.data!.data == null || deviceListEntity.data!.data!.isEmpty
            ? Container(
          child: Column(
            children: [
              _getHeadItem(
                  widget.patientInfoCustom.name ?? '',
                  widget.patientInfoCustom.sex ?? '男',
                  widget.patientInfoCustom.age ?? 0,
                  widget.patientInfoCustom.mobile ?? ''),
              VerPadding(120.h),
              Image.asset(
                searchEmptyPng,
                width: 71.w,
                height: 52.h,
              ),
              VerPadding(15.h),
              F12TitleText('暂无设备信息', color: F2TextColor),
              Expanded(child: Container()),
              Container(
                margin: EdgeInsets.symmetric(horizontal: 30.w, vertical: 25.h),
                child: CommonBtn(
                  title: '分配设备',
                  callback: (){
                    NavigatorUtil.push(context, DeliveryDevicePage(patientInfoCustom: widget.patientInfoCustom,labelList: widget.labelList ?? [],patientLabelModel: widget.labelModel));
                  },
                ),
              ),
            ],
          ),
        )
            : Stack(
                children: [
                  Positioned(
                      left: 0,
                      right: 0,
                      top: 0,
                      bottom: deviceListEntity.data!.data!.first!.status! == 0 ? 100.h : 0,
                      child: ListView.separated(
                        itemBuilder: (ctx, index) {
                          if (index == 0) {
                            return _getHeadItem(
                                widget.patientInfoCustom.name ?? '',
                                widget.patientInfoCustom.sex ?? '男',
                                widget.patientInfoCustom.age ?? 0,
                                widget.patientInfoCustom.mobile ?? '');
                          } else {
                            return _getDeviceItem(index - 1);
                          }
                        },
                        itemCount: deviceListEntity.data!.data!.length + 1,
                        separatorBuilder: (BuildContext context, int index) {
                          return Divider(
                            height: 10,
                            thickness: 10,
                            color: Colors.transparent,
                          );
                        },
                      )),
                  Positioned(
                    child: Visibility(
                      visible: deviceListEntity.data!.data!.first!.status! == 0,
                      child: Container(
                        margin: EdgeInsets.symmetric(horizontal: 30.w, vertical: 25.h),
                        child: CommonBtn(
                          title: '分配设备',
                          callback: (){
                            NavigatorUtil.push(context, DeliveryDevicePage(patientInfoCustom: widget.patientInfoCustom,labelList: widget.labelList ?? [],patientLabelModel: widget.labelModel,));
                          },
                        ),
                      ),
                    ),
                    left: 0,
                    right: 0,
                    bottom: 0,
                    height:  deviceListEntity.data!.data!.first!.status! == 0 ? 100.h : 0,
                  )
                ],
              ));
  }

  Widget _getHeadItem(String name, String sex, int age, String mobile) {
    if (name.length > 4) {
      return Container(
        margin: EdgeInsets.symmetric(horizontal: 15.w),
        height: 85.h,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(7.5.w)),
            color: themeColor),
        child: Column(
          children: [
            VerPadding(10.h),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                HorPadding(17.w),
                Image.asset(
                  sex == '男' ? patientMaleImg : patientFemaleImg,
                  width: 35.w,
                  height: 35.w,
                ),
                HorPadding(6.w),
                Container(constraints: BoxConstraints(maxWidth: ScreenUtil().screenWidth-140.w), child: MyText(name, color: Colors.white, fontSize: 20, overflow: TextOverflow.ellipsis,)),
                HorPadding(10.w),
                Container(
                  width: 20.w,
                  height: 20.w,
                  decoration: BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage(
                              sex == '男' ? hospitalMaleIcon : hospitalFemaleIcon),
                          fit: BoxFit.none,
                          scale: 4.5),
                      color: Color(0xFFDEE5FB),
                      borderRadius: BorderRadius.all(Radius.circular(10.w))),
                ),
                HorPadding(10.w),
              ],
            ),
            VerPadding(8.h),
            Row(
              children: [
                HorPadding(20.w),
                F14TitleText('$age岁', color: Colors.white),
                HorPadding(5.w),
                F14TitleText(mobile, color: Colors.white),
                HorPadding(17.w),
              ],
            )
          ],
        ),
      );
    } else {
      return Container(
        margin: EdgeInsets.symmetric(horizontal: 15.w),
        height: 65.h,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(7.5.w)),
            color: themeColor),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            HorPadding(17.w),
            Image.asset(
              sex == '男' ? patientMaleImg : patientFemaleImg,
              width: 35.w,
              height: 35.w,
            ),
            HorPadding(6.w),
            MyText(name, color: Colors.white, fontSize: 20),
            HorPadding(5.w),
            Container(
              width: 20.w,
              height: 20.w,
              decoration: BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage(
                          sex == '男' ? hospitalMaleIcon : hospitalFemaleIcon),
                      fit: BoxFit.none,
                      scale: 4.5),
                  color: Color(0xFFDEE5FB),
                  borderRadius: BorderRadius.all(Radius.circular(10.w))),
            ),
            Expanded(child: Container()),
            F14TitleText('$age岁', color: Colors.white),
            HorPadding(5.w),
            F14TitleText(mobile, color: Colors.white),
            HorPadding(17.w),
          ],
        ),
      );
    }

  }

  Widget _getDeviceItem(int id) {
    PatientDeviceListDataData data = deviceListEntity.data!.data![id];

    double widgetHeight = 0.h;
    List<FlagModel> labels = [];
    if (widget.labelList != null) {
      for (int i = 0; i < widget.labelList!.length; i++) {
        AcquisitionAcquisitionLabelList label = widget.labelList![i];
        Color color = ColorUtils.getColorFromHex(label.colour!);
        LogUtils.log('name=${label.name}');
        labels
            .add(FlagModel(label.name!, false, color.withOpacity(0.2), color));
      }
    }

    List<Widget> models = FlagsWidget.getFlagsWidget2(
        labels, ScreenUtil().screenWidth - 150.w, 70, 10, (_widgetHeight) {
      widgetHeight = _widgetHeight;
    });
    return Container(
        padding: EdgeInsets.symmetric(horizontal: 15.w),
        height: labels.isEmpty ? 125.h : 150.h + widgetHeight,
        width: ScreenUtil().screenWidth - 30.w,
        margin: EdgeInsets.symmetric(horizontal: 15.w),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(7.5.h))),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            VerPadding(20.h),
            Row(
              children: [
                MyText(data.distributionTime == null ? '' : data.distributionTime!.split(' ')[0],
                    color: Color(0xFF262626), fontSize: 17),
                Expanded(child: Container()),
                F12TitleText(data.status == 0 ? '已回收' : '使用中',
                    color: data.status == 0 ? Color(0xFF118191) : Color(0xFFED5089)),
                HorPadding(15.w),
                Visibility(
                  visible: data.status != 0,
                  child: GestureDetector(
                    onTap: () {
                      recycleWidget(data);
                    },
                    child: Container(
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: themeColor,
                            borderRadius:
                                BorderRadius.all(Radius.circular(15.5))),
                        width: 65.w,
                        height: 31.h,
                        child: F12TitleText(
                          '回收设备',
                          color: Colors.white,
                        )),
                  ),
                ),
              ],
            ),
            F13TitleText('设备类型：脑电一体机', color: Color(0xFF262626)),
            VerPadding(6.h),
            F13TitleText('设备名称：${data.deviceBluetoothNumber ?? ''}',
                color: Color(0xFF262626)),
            VerPadding(6.h),
            F13TitleText('脑贴名称：${data.bmDeviceBluetoothNumber ?? ''}',
                color: Color(0xFF262626)),
            VerPadding(6.h),
            Row(
              children: labels.isEmpty ? [] : [
                F13TitleText('采集标签：', color: Color(0xFF262626)),
                Container(
                  height: widgetHeight,
                  width: ScreenUtil().screenWidth - 150.w,
                  child: Stack(children: models),
                ),
                HorPadding(15.w)
              ],
            )
          ],
        ));
  }

  ///回收设备窗口
  Future<void> recycleWidget(PatientDeviceListDataData data) async {
    CustomRecycleMode model = CustomRecycleMode(data.createTime, data.deviceId,
      data.deviceNumber, data.bmDeviceBluetoothNumber, widget.labelList, data.distributionName, '', '', data.deviceBluetoothNumber);
    entry = OverlayEntry(builder: (ctx) {
      return RecycleDeviceAlert(
        customRecycleMode: model,
        entry: entry!,
        callback: (id, time, remark) {
          if (id == 1) {
            recycleTime = time;
            recycleRemark = recycleRemark;
            recycleDevice(data, time, remark);
          }
        },
      );
    });
    Overlay.of(context).insert(entry!);
  }

  ///回收设备逻辑
  void recycleDevice(
      PatientDeviceListDataData data, String time, String remark) {

    deviceInfoSubscription = globalEventBus.on<DeviceInfoModel>().listen((onData) async {
      mqttCancelSubscribe(topic!);
      deviceInfoSubscription!.cancel();
      if (!isQueryRecycle) {
        return;
      }
      isQueryRecycle = false;
      queryTimer?.cancel();
      // if (onData.aioWorkStatus == 'Y') {
      //   ToastUtils.showToast(msg: '终端正在工作中，暂时不能回收');
      //   return;
      // }
      // LogUtils.log('work=${onData.workStatus}');
      // if (onData.workStatus == 'Y') {
      //   ToastUtils.showToast(msg: '终端正在工作中，暂时不能回收');
      //   return;
      // }
      if (onData.aioWifiStatus != 'Y') {
        entry = OverlayEntry(builder: (ctx){
          return CommonAlert(title: '一体机断网', msg: '一体机Wi-Fi断开，请重连', callback: (id){
            if (id == 1) {
              NavigatorUtil.push(context, WifiSetPage());
            }
          }, entry: entry!, leftBtnText: '取消', rightBtnText: 'Wi-Fi连接',);
        });
        Overlay.of(context).insert(entry!);
        return;
      }

      await Future.delayed(const Duration(seconds: 2));
      Loading.getIns().hide();

      ///mqtt 通知一体机
      Map<String, dynamic> msg = {};
      msg['messageType'] = mqttRecycleDevice;
      msg['data'] = {
        'token': PreferencesHelper.getUserToken(),
        'sickPersonId': widget.patientInfoCustom.userId!
      };
      mqttPublicMsg('RL/SAAS/$curDeviceName/APP', convert.jsonEncode(msg));
      mqttSubscribe('RL/SAAS/$curDeviceName');

      Loading.getIns().loading(msg: '正在回收设备');
      recycleTimer = Timer(Duration(seconds: 20), () {
        Loading.getIns().hide();
        mqttCancelSubscribe('RL/SAAS/$curDeviceName');
        recycleSubscription!.cancel();
      });

      recycleSubscription =
          globalEventBus.on<RecycleDeviceModel>().listen((recycleModel) {
            ///取消订阅
            mqttCancelSubscribe('RL/SAAS/$curDeviceName');
            recycleSubscription!.cancel();
            recycleTimer?.cancel();
            Loading.getIns().hide();
            if (recycleModel.result) {
              NetBusiness().unbindDevice(curDeviceId!, time, remark).then((onValue) {
                if (onValue) {
                  ToastUtils.showToast(msg: '设备回收成功');
                  ///刷新界面
                  NetBusiness().patientDeviceList(widget.patientInfoCustom.userId).then((onValue) {
                    setState(() {
                      deviceListEntity = onValue;
                    });
                  });
                  globalEventBus.fire(EventBufRefreshModel());
                }
              });
            } else {
              ToastUtils.showToast(msg: '设备回收失败');
            }
          });
      // NetBusiness()
      //     .unbindDevice(curDeviceId!, recycleTime!, recycleRemark)
      //     .then((onValue) {
      //   if (onValue) {
      //     ToastUtils.showToast(msg: '设备回收成功');
      //
      //     ///刷新界面
      //     NetBusiness().patientDeviceList(widget.patientInfoCustom.userId).then((onValue) {
      //       setState(() {
      //         deviceListEntity = onValue;
      //       });
      //     });
      //
      //     globalEventBus.fire(EventBufRefreshModel());
      //
      //     ///mqtt 通知一体机
      //     Map<String, dynamic> msg = {};
      //     msg['messageType'] = mqttRecycleDevice;
      //     msg['data'] = {
      //       'token': PreferencesHelper.getUserToken(),
      //       'sickPersonId': widget.patientInfoCustom.userId!
      //     };
      //
      //     mqttPublicMsg('RL/SAAS/$curDeviceName/APP', convert.jsonEncode(msg));
      //   }
      // });
    });

    curDeviceName = data.deviceBluetoothNumber;
    curDeviceId = data.deviceId;
    topic = 'RL/SAAS/${data.deviceBluetoothNumber}';

    Loading.getIns().loading(msg: '正在查询终端状态');
    queryTimer = Timer(Duration(seconds: 10), (){
      Loading.getIns().hide();
      ToastUtils.showToast(msg: '查询终端状态超时');
    });
    isQueryRecycle = true;

    mqttSubscribe(topic!);
    String pubTopic = 'RL/SAAS/${data.deviceBluetoothNumber}/APP';
    Map<String, dynamic> msg = {'messageType': mqttDeviceInfo};
    mqttPublicMsg(pubTopic, convert.jsonEncode(msg));
  }
}
